import random, string, json
from django.utils.timezone import now
from django.db import models
from user.models import UserProfile
from django_redis import get_redis_connection
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

# Create your models here.


class ChatSession(models.Model):
    userID = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='用户ID')
    chatID = models.CharField(max_length=32, verbose_name='会话ID', primary_key=True)
    creat_time = models.DateTimeField(verbose_name='会话创建时间', default=now().strftime("%Y-%m-%d %H:%M:%S"))
    state = models.BooleanField(default=True, verbose_name='可用状态')

    class Meta:
        db_table = 'chatSession'
        verbose_name = '会话列表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.userID.username


class ChatHistory(models.Model):
    chatID = models.ForeignKey(ChatSession, on_delete=models.CASCADE, verbose_name='会话创建者')
    title = models.CharField(max_length=500, verbose_name='标题', default='新的会话')
    message = models.JSONField(verbose_name='聊天内容', default=list)
    send_token = models.IntegerField(default=0, verbose_name='用户发送使用Token')
    receive_token = models.IntegerField(default=0, verbose_name='用户接收使用Token')

    class Meta:
        db_table = 'chatHistory'
        verbose_name = '聊天记录'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.chatID.chatID


class Mask(models.Model):
    MODEL_CHOICE = (
        (0, 'gpt-3.5-turbo'),
        (1, 'gpt-4'),
    )

    maskId = models.CharField(max_length=16, verbose_name='面具ID', null=False, primary_key=True, unique=True, editable=False)
    title = models.CharField(max_length=50, verbose_name='面具名称', null=False)
    desc = models.CharField(max_length=1000, verbose_name='描述词', null=False, help_text='此处填写面具的预设对话，角色是system，请调试好再填写，多条预设对话用 | 分割')
    model = models.SmallIntegerField(verbose_name='模型', default=0, choices=MODEL_CHOICE)

    def save(self, *args, **kwargs):
        self.maskId = self.generate_mask_id()
        super().save(*args, **kwargs)

    def generate_mask_id(self):
        return ''.join(random.choices(string.ascii_letters + string.digits, k=16))

    class Meta:
        db_table = 'mask'
        verbose_name = '面具'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title


@receiver(post_save, sender=Mask)
def save_mask_to_redis(sender, instance, **kwargs):
    key = instance.maskId
    data = {
        "title": instance.title,
        "desc": instance.desc,
        "model": instance.get_model_display()
    }
    connect = get_redis_connection('mask')
    connect.set(key, json.dumps(data))


@receiver(post_delete, sender=Mask)
def delete_mask_from_redis(sender, instance, **kwargs):
    connect = get_redis_connection('mask')
    connect.delete(instance.maskId)
